<?php
/**
 * Created by PhpStorm.
 * User: banyunba
 * Date: 2017/10/1
 * Time: 下午8:43
 */

namespace org;

use think\Db;
use think\Exception;
use think\cache\driver\Redis;

class RedisHash
{
    public $redisHash = null;//redis实例化时静态变量

    static protected $instance;
    protected $sn;
    protected $index = 8;
    protected $table ;
    public $hashKey;

    public function __construct($options=[]){
        $host = trim(isset($options["host"]) ? $options["host"] : '123.57.13.117');
        $port = trim(isset($options["port"]) ? $options["port"] :  6378 );
        $auth = trim(isset($options["password"]) ? $options["password"] :  "r-2zebbc97f112be94:Redis123" );
        $index = trim(isset($options["select"]) ? $options["select"] : 8 );

        if (!is_integer($index) && $index>16) {
            $index = 11;
        }
        $sn = md5("{$host}{$port}{$auth}{$index}");
        $this->sn = $sn;
        if (!isset($this->redisHash[$this->sn])){
             $options = [
                'host'       => $host,
                'port'       => $port,
                'password'   => $auth,
                'select'     => $index,
                'timeout'    => 0,
                'expire'     => 0,
                'persistent' => false,
                'prefix'     => '',
            ];
            $this->redisHash[$this->sn] = new Redis($options);
        }
        $this->redisHash[$this->sn]->sn = $sn;
        $this->index = $index;
        return ;
    }


    /**
     * 返回list区间元素
     * @param $name
     * @param int $start
     * @param int $end
     * @return array
     */
    public function lrange ($name,$start = 0,$end = -1)
    {
        return $this->redisHash[$this->sn]->lrange($name,$start,$end);
    }

    /**
     * 返回list长度
     * @param string $key
     * @return mixed
     */
    public function llen ($key = '')
    {
        return $this->redisHash[$this->sn]->llen($key);
    }

    /**
     * rPush list
     * @param $field
     * @param $value
     * @return mixed
     */
    public function rPush ($field,$value)
    {
        return $this->redisHash[$this->sn]->rPush($field,$value);
    }

    /**
     * 设置缓存
     * @param $field
     * @param $value
     * @param null $expire
     * @return mixed
     */
    public function set ($field, $value, $expire = null)
    {
        return $this->redisHash[$this->sn]->set($field,$value,$expire);
    }

    /**
     * 单例
     * @param array $options
     * @return RedisHash
     */
    public static function instance($options=[])
    {
        return  new RedisHash($options);
    }


    /**
     * 魔术方法 有不存在的操作的时候执行
     * @access public
     * @param string $method 方法名
     * @param array $args 参数
     * @return mixed
     */
    public function __call($method, $args)
    {
        call_user_func_array([$this->redisHash[$this->sn], $method], $args);
    }

}